using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.Core;

namespace Forum.Business
{
    public class PostEdit : ForumUserControl,
        IReplyConverter<PostReply, GetOperation>
    {
        protected ValuedEditor bodyEditor;
        protected ResourceButton saveButton;

        private Post post;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetPostRequest(this));
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!ValidatePermission(PermissionType.EditPost))
            {
                throw new Exception("Access denied.");
            }
            saveButton.Click += new EventHandler(SavePost);
        }

        private void SavePost(object sender, EventArgs e)
        {
            if (post != null)
            {
                post.Body.Value = bodyEditor.Value;
                BusinessManager.UpdatePost(post);
            }
            Page.Response.Redirect(UrlManager.Instance.FormatUrl("post_list",post.ThreadId));
        }

        #region IReplyConverter<PostReply,GetOperation> Members

        public void ConvertReply(PostReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                post = reply.Entity as Post;

                if (!IsPostBack)
                {
                    bodyEditor.Value = post.Body.Value;
                }
            }
        }

        #endregion
    }
}